import datetime
import uuid

from django.contrib.auth import get_user_model
from django.contrib.auth.models import AbstractUser
from django.db import models

# Create your models here.


class UserProfile(AbstractUser):
    """用户信息"""
    uuid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    hobby = models.ForeignKey('Hobby', on_delete=models.CASCADE, related_name='hobby_users', default=None, blank=True, null=True)
    picture = models.ImageField("个人照片", upload_to='portrait/', null=True, blank=True)
    nick_name = models.CharField("真实姓名", max_length=255, null=True, blank=True, help_text='实名')
    email = models.EmailField("邮箱", max_length=255, null=True, blank=True)
    mobile = models.CharField("手机号", max_length=255, null=True, blank=True)
    is_delete = models.BooleanField(default=0)

    def __str__(self):
        return f'{self.nick_name}'


class Hobby(models.Model):
    """兴趣爱好"""
    uuid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(help_text="手机号", max_length=255, null=True, blank=True)
    add_time = models.DateTimeField(default=datetime.datetime.now)
    is_delete = models.BooleanField(default=0)

    def __str__(self):
        return f'{self.name}'


class Friend(models.Model):
    uuid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey('UserProfile', on_delete=models.CASCADE, related_name='all_users')
    is_Stick = models.BooleanField(default=0, help_text='置顶')
    blacklist = models.BooleanField(default=0, help_text='黑名单')
    friend = models.ForeignKey('UserProfile', on_delete=models.CASCADE, related_name='all_friends')
    relation = models.CharField(help_text="关系类型", max_length=255, null=True, blank=True)
    add_time = models.DateTimeField(default=datetime.datetime.now)
    is_delete = models.BooleanField(default=0)

    def delete(self, using=None, keep_parents=False):
        self.is_delete = True
        self.save()

    def __str__(self):
        return f'{self.user.nick_name} 好友 {self.friend.nick_name}'

    def add_blacklist(self):
        self.blacklist = 1
        self.is_delete = True
        self.save()

    def relieve_blacklist(self):
        self.blacklist = 0
        self.save()

    class Meta:
        unique_together = ('user', 'friend')


class MessageQuerySet(models.query.QuerySet):

    def get_conversation(self, sender, recipient):
        """用户间的私信会话"""
        qs_one = self.filter(sender=sender, recipient=recipient).select_related('sender', 'recipient')  # A发送给B的消息
        qs_two = self.filter(sender=recipient, recipient=sender).select_related('sender', 'recipient')  # B发送给A的消息
        return qs_one.union(qs_two).order_by('created_at')  # 取并集后按时间排序

    def get_most_recent_conversation(self, recipient):
        """获取最近一次私信互动的用户"""
        try:
            qs_sent = self.filter(sender=recipient).select_related('sender', 'recipient')  # 当前登录用户发送的消息
            qs_received = self.filter(recipient=recipient).select_related('sender', 'recipient')  # 当前登录用户接收的消息
            qs = qs_sent.union(qs_received).latest("created_at")  # 最后一条消息
            if qs.sender == recipient:
                # 如果登录用户有发送消息，返回消息的接收者
                return qs.recipient
            # 否则返回消息的发送者
            return qs.sender
        except self.model.DoesNotExist:
            # 如果模型实例不存在，则返回当前用户
            return get_user_model().objects.get(username=recipient.username)


class Message(models.Model):
    """用户间私信"""
    uuid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    sender = models.ForeignKey(UserProfile, related_name='sent_messages',
                               blank=True, null=True, on_delete=models.SET_NULL, verbose_name='发送者')
    recipient = models.ForeignKey(UserProfile, related_name='received_messages',
                                  blank=True, null=True, on_delete=models.SET_NULL, verbose_name='接受者')
    message = models.TextField(blank=True, null=True, verbose_name='内容')
    unread = models.BooleanField(default=True, verbose_name='是否未读')
    created_at = models.DateTimeField(db_index=True, auto_now_add=True, verbose_name='创建时间')
    is_delete = models.BooleanField(default=0)

    objects = MessageQuerySet.as_manager()

    class Meta:
        verbose_name = '私信'
        verbose_name_plural = verbose_name
        ordering = ('-created_at',)

    def __str__(self):
        return self.message

    def mark_as_read(self):
        if self.unread:
            self.unread = False
            self.save()


class ChatRoom(models.Model):
    """聊天组"""
    uuid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    room_name = models.CharField(help_text="组名", max_length=255, null=True, blank=True)
    room_picture = models.ImageField()
    creator = models.ForeignKey(UserProfile, related_name='user_room',
                               blank=True, null=True, on_delete=models.SET_NULL, verbose_name='创建者')
    is_delete = models.BooleanField(default=0, help_text='是否删除')
    created_at = models.DateTimeField(db_index=True, auto_now_add=True, verbose_name='创建时间')


class GroupMember(models.Model):
    """聊天室成员"""
    uuid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    ROLE = ((0, '普通成员'), (1, '管理员'), (2, '群主'))
    group = models.ForeignKey(ChatRoom, related_name='all_room',
                               blank=True, null=True, on_delete=models.SET_NULL, verbose_name='聊天组')
    member = models.ForeignKey(UserProfile, related_name='all_member',
                               blank=True, null=True, on_delete=models.SET_NULL, verbose_name='组用户')
    group_nick_name = models.CharField(help_text="组员昵称", max_length=255, null=True, blank=True)
    group_role = models.IntegerField(help_text="成员角色", default=0, choices=ROLE)
    is_delete = models.BooleanField(default=0, help_text='是否删除')
    join_date = models.DateTimeField(db_index=True, auto_now_add=True, verbose_name='加入时间')


class GroupFile(models.Model):
    """聊天室文件"""
    uuid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    group = models.ForeignKey(ChatRoom, related_name='group_file',
                               blank=True, null=True, on_delete=models.SET_NULL, verbose_name='聊天组')
    users = models.ForeignKey(UserProfile, related_name='group_file_users',
                               blank=True, null=True, on_delete=models.SET_NULL, verbose_name='文件上传者')
    group_file = models.FileField()
    is_delete = models.BooleanField(default=0, help_text='是否删除')
    upload_date = models.DateTimeField(db_index=True, auto_now_add=True, verbose_name='上传时间')


class GroupMessage(models.Model):
    """聊天组消息"""
    MSG_TYPE = ((1, '邀请'), (2, '消息'), (3, '其他'), (4, '管理员'))
    uuid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    sender = models.ForeignKey(UserProfile, related_name='group_sent_messages',
                               blank=True, null=True, on_delete=models.SET_NULL, verbose_name='发送者')
    msg_type = models.IntegerField(choices=MSG_TYPE, default=2)
    group = models.ForeignKey(ChatRoom, related_name='received_messages',
                                  blank=True, null=True, on_delete=models.SET_NULL, verbose_name='聊天组')
    message = models.TextField(blank=True, null=True, verbose_name='内容')
    created_at = models.DateTimeField(db_index=True, auto_now_add=True, verbose_name='创建时间')
    is_delete = models.BooleanField(default=0)
